import Taro from '@tarojs/taro';
import { useState, useEffect } from "react";
import { View, Button, Picker } from '@tarojs/components';
import { AtInput, AtForm, AtImagePicker, AtTextarea, AtMessage, AtIcon, AtToast } from 'taro-ui';
import { createActivity } from "@/api/application/volunteer";
import "taro-ui/dist/style/components/button.scss"; // 按需引入
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/image-picker.scss";
import "taro-ui/dist/style/components/icon.scss";
import Header from '@/components/header';
import Return from '@/components/Return';
import SubmitOkModal from '@/components/SubmitOkModal';
import css from './index.module.less';
import './index.less';

export default function CreateActivity() {

  //表单各项的值
  const [userInfo, setUserInfo] = useState({});
  const [activityTitle, setActivityTitle] = useState("");
  const [activityContent, setActivityContent] = useState("");
  const [activityLocation, setActivityLocation] = useState("");
  const [meetingPlace, setMeetingPlace] = useState("");
  const [activityContact, setActivityContact] = useState("");
  const [contactNumber, setContactNumber] = useState("");
  const [activityTime, setActivityTime] = useState("");
  const [registrationDeadline, setRegistrationDeadline] = useState("");
  //上传文件相关数据
  const [imgs, setImgs] = useState([]);
  const [files, setFiles] = useState([]);
  const [imgIds, setImgIds] = useState([]);
  const [fileIds, setFileIds] = useState([]);
  //提交成功弹窗的可见性
  const [submitOkVis, setSubmitOkVis] = useState(false);
  //加载中
  const [isOpened, setIsOpened] = useState(false);

  useEffect(() => {
    setActivityTime(getCurTime());
    setRegistrationDeadline(getCurTime());
    Taro.getStorage({
      key: 'userInfo',
      success: function (info) {
        setUserInfo(info.data);
      }
    });
  }, []);

  useEffect(() => {
    if (imgs.length > 0) {
      if (imgIds.length < imgs.length) {
        uploadImgFiles(imgIds.length);
      }
      else if (imgIds.length === imgs.length) uploadExtraFiles(0);
    }
  }, [imgIds]);
  useEffect(() => {
    if (files.length > 0) {
      if (fileIds.length < files.length) {
        uploadExtraFiles(fileIds.length);
      }
      else if (fileIds.length === files.length) create();
    }
  }, [fileIds]);

  const getCurTime = () => {
    const curYear = (new Date()).getFullYear();
    let curMonth = (new Date()).getMonth() + 1;
    if (curMonth < 10) curMonth = "0" + curMonth;
    const curDay = (new Date()).getDate();
    return curYear + "-" + curMonth + "-" + curDay;
  };

  const imgOnChange = (tempImgs) => {
    const validFiles = tempImgs.filter(file => file.file.size / 1024 / 1024 < 1);
    if (validFiles.length !== tempImgs.length) tipMessage('文件大小不能超过 1M');
    if (validFiles.length <= 9) setImgs([...validFiles]);
    else tipMessage('附件最大上传数 9');
  };

  const fileOnChange = () => {
    Taro.chooseMessageFile({
      success: function (res) {
        const validFiles = res.tempFiles.filter(file => file.size / 1024 / 1024 < 1);
        if (validFiles.length !== res.tempFiles.length) tipMessage('文件大小不能超过 1M');
        if (files.length + validFiles.length <= 9) setFiles([...files, ...validFiles]);
        else tipMessage('附件最大上传数 9');
      }
    });
  };

  const fileRemove = (e, index) => {
    files.splice(index, 1);
    setFiles([...files]);
  };

  const tipMessage = (text) => {
    Taro.atMessage({ 'message': text, 'type': 'warning', 'duration': 2000 });
  };

  const isValid = () => {
    if (activityTitle === "") {
      tipMessage('请填写标题');
      return false;
    }
    else if (activityTitle.length < 5) {
      tipMessage('标题长度不能小于5');
      return false;
    }
    else if (activityContent === "") {
      tipMessage('请填写内容');
      return false;
    }
    else if (activityLocation === "") {
      tipMessage('请填写活动地址');
      return false;
    }
    else if (meetingPlace === "") {
      tipMessage('请填写集合地址');
      return false;
    }
    else if (activityContact === "") {
      tipMessage('请填写组织者姓名');
      return false;
    }
    else if (contactNumber === "") {
      tipMessage('请填写联系方式');
      return false;
    }
    else if (!/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(contactNumber)) {
      tipMessage('请填写正确的联系方式');
      return false;
    }
    else if (activityTime === "") {
      tipMessage('请选择集合时间');
      return false;
    }
    else if (registrationDeadline === "") {
      tipMessage('请选择报名截止时间');
      return false;
    }
    return true;
  };

  function uploadImgFiles(index) {
    if (imgs.length > 0) {
      Taro.uploadFile({
        url: 'http://localhost:8082/oss/upload/service_volunteer_activity/0/img',
        filePath: imgs[index].url,
        name: "file",
        success: function (resImg) {
          imgIds.push(JSON.parse(resImg.data).data.id);
          setImgIds([...imgIds]);
        },
      });
    }
    else uploadExtraFiles(0);
  }

  function uploadExtraFiles(index) {
    if (files.length > 0) {
      Taro.uploadFile({
        url: 'http://localhost:8082/oss/upload/service_volunteer_activity/0/file',
        filePath: files[index].path,
        name: "file",
        success: function (resExtra) {
          fileIds.push(JSON.parse(resExtra.data).data.id);
          setFileIds([...fileIds]);
        },
      });
    }
    else create();
  }

  const create = () => {
    const { partyId } = userInfo;
    const info = {
      activityContact,
      activitySponsorId: partyId,
      activityContent, activityLocation,
      activityTitle, fileIds, imgIds,
      contactNumber, meetingPlace,
      registrationDeadline: registrationDeadline + " 23:59:59",
      activityTime: activityTime + " 00:00:00",
    };
    createActivity(info).then(res => {
      if (res.code === 200) {
        setSubmitOkVis(true);
      }
      else if (res.message.code === 500) {
        tipMessage(res.message.message);
      }
    }).finally(() => { setIsOpened(false); });
  };

  const onSubmit = () => {
    if (isValid()) {
      setIsOpened(true);
      uploadImgFiles(0);
    }
  };

  const preView = () => {
    if (isValid()) {
      const { partyId, name, organizationName } = userInfo;
      const formData = {
        name, organizationName,
        activityContact, activitySponsorId: partyId,
        activityContent, activityLocation,
        activityTitle, files, imgs,
        contactNumber, meetingPlace,
        registrationDeadline: registrationDeadline + " 23:59:59",
        activityTime: activityTime + " 00:00:00",
      };
      Taro.navigateTo({ url: `previewAct/index?data=${JSON.stringify(formData)}` });
    }
  };

  return (
    <View className={css.home}>
      <Header message='创建活动' left='140px' />
      <Return />
      <AtForm className={css.form} onSubmit={onSubmit}>
        <AtMessage />
        <View className={css.formItem}>
          <AtInput
            name='title'
            title='活动标题'
            required
            value={activityTitle}
            onChange={e => { setActivityTitle(e); }}
            placeholder='请输入5字以上的活动标题'
          />
        </View>
        <View className={css.formItem}>
          <View className={`required ${css.lable}`}>活动内容</View>
          <AtTextarea
            value={activityContent}
            onChange={e => { setActivityContent(e); }}
            placeholder='请输入活动内容'
            maxLength={1000}
            count
            height={600}
          />
        </View>
        <View className={css.formItem}>
          <AtInput
            name='activityLocation'
            title='活动地址'
            required
            value={activityLocation}
            onChange={e => { setActivityLocation(e); }}
            placeholder='请输入活动地址'
          />
        </View>
        <View className={css.formItem}>
          <AtInput
            name='meetingPlace'
            title='集合地址'
            required
            value={meetingPlace}
            onChange={e => { setMeetingPlace(e); }}
            placeholder='请输入集合地址'
          />
        </View>
        <View className={css.formItem}>
          <AtInput
            name='name'
            title='组织者姓名'
            required
            value={activityContact}
            onChange={e => { setActivityContact(e); }}
            placeholder='请输入组织者姓名'
          />
        </View>
        <View className={css.formItem}>
          <AtInput
            name='contact'
            title='联系方式'
            required
            value={contactNumber}
            type='number'
            onChange={e => { setContactNumber(e); }}
            placeholder='请输入联系方式'
          />
        </View>
        <View className={css.formItem}>
          <View className={css.selector}>
            <View className={`required ${css.lable}`}>集合时间</View>
            <Picker
              mode='date'
              start={getCurTime()}
              value={activityTime}
              onChange={e => { setActivityTime(e.detail.value); }}
            >
              <View className={css.text}>{activityTime}</View>
            </Picker>
          </View>
        </View>
        <View className={css.formItem}>
          <View className={css.selector}>
            <View className={`required ${css.lable}`}>报名截止</View>
            <Picker
              mode='date'
              start={getCurTime()}
              value={registrationDeadline}
              onChange={e => { setRegistrationDeadline(e.detail.value); }}
            >
              <View className={css.text}>{registrationDeadline}</View>
            </Picker>
          </View>
        </View>
        <View className={css.formItem}>
          <View className={css.lable}>上传图片:</View>
          <AtImagePicker
            files={imgs}
            onChange={imgOnChange}
            count={9}
            length={3}
            multiple
            mode='scaleToFill'
          />
        </View>
        <View className={css.formItem}>
          <View className={css.lable}>上传文件:</View>
          <View>
            <Button type='warn' plain size='mini' onClick={fileOnChange}>+ 上传文件</Button>
            {
              files.map((file, index) => (
                <View key={index} className={css.file}>
                  <AtIcon value='file-generic' size='18rpx' color='rgb(154,154,154)' />
                  {file.name}
                  <AtIcon
                    value='trash'
                    size='18rpx'
                    color='rgb(154,154,154)'
                    onClick={e => fileRemove(e, index)}
                  />
                </View>
              ))
            }
            <View className={css.tip}>支持拓展名: .doc .docx .pdf .jpg...</View>
          </View>
        </View>
        <View className={css.buttonBox}>
          <Button plain className={css.submitBtn} formType='submit'>提交</Button>
          <Button plain className={css.previewBtn} onClick={preView}>预览</Button>
        </View>
      </AtForm>

      <SubmitOkModal visible={submitOkVis} setVisible={setSubmitOkVis} url='../../index' text='志愿活动' />

      <AtToast isOpened={isOpened} text='上传数据中...' status='loading' duration={0} hasMask />
    </View>
  );
}